import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; documentId: string }> }
) {
  try {
    const { id: projectId, documentId } = await params;
    const body = await request.json();
    const { content } = body;
    
    if (!content) {
      return NextResponse.json({ error: '内容不能为空' }, { status: 400 });
    }

    // 将 content 对象转换为 JSON 字符串
    const contentString = typeof content === 'string' ? content : JSON.stringify(content);

    // 确保临时用户存在
    let tempUser = await prisma.user.findUnique({
      where: { id: 'temp-user' }
    });

    if (!tempUser) {
      tempUser = await prisma.user.create({
        data: {
          id: 'temp-user',
          name: '临时用户',
          email: 'temp@example.com'
        }
      });
    }

    // 检查项目是否存在，如果不存在则创建
    let project = await prisma.project.findUnique({
      where: { id: projectId }
    });

    if (!project) {
      project = await prisma.project.create({
        data: {
          id: projectId,
          name: '默认项目',
          description: '自动创建的项目',
          createdById: 'temp-user'
        }
      });
    }

    let document = await prisma.document.findUnique({
      where: { id: documentId }
    });

    if (!document) {
      document = await prisma.document.create({
        data: {
          id: documentId,
          title: '协作文档',
          content: contentString,
          version: 1,
          projectId,
          createdById: 'temp-user',
          updatedById: 'temp-user'
        }
      });
    } else {
      document = await prisma.document.update({
        where: { id: documentId },
        data: {
          content: contentString,
          version: (document.version || 0) + 1,
          updatedAt: new Date(),
          updatedById: 'temp-user'
        }
      });
    }
    
    // 返回时将 content 转换回对象
    const responseDocument = {
      ...document,
      content: typeof document.content === 'string' ? JSON.parse(document.content) : document.content
    };
    
    return NextResponse.json(responseDocument);
    
  } catch (error) {
    console.error('API错误:', error);
    return NextResponse.json(
      { error: '服务器错误', details: error.message },
      { status: 500 }
    );
  }
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; documentId: string }> }
) {
  try {
    const { documentId } = await params;
    
    let document = await prisma.document.findUnique({
      where: { id: documentId }
    });

    if (!document) {
      return NextResponse.json({
        id: documentId,
        title: '协作文档',
        content: { type: "doc", content: [] },
        version: 0
      });
    }
    
    // 将存储的 JSON 字符串转换回对象
    const responseDocument = {
      ...document,
      content: typeof document.content === 'string' ? JSON.parse(document.content) : document.content
    };
    
    return NextResponse.json(responseDocument);
    
  } catch (error) {
    console.error('获取文档错误:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}
